package com.myproject.mall.seller.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.myproject.mall.common.exception.GlobalException;
import com.myproject.mall.domain.dto.ShopDTO;
import com.myproject.mall.domain.entity.Goods;
import com.myproject.mall.domain.entity.Shop;
import com.myproject.mall.domain.entity.User;
import com.myproject.mall.domain.enums.ShopStatus;
import com.myproject.mall.domain.vo.ShopVO;
import com.myproject.mall.seller.mapper.ShopMapper;
import com.myproject.mall.seller.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class ShopServiceImpl implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public ShopDTO getShopInfo(Long id) {
        MPJLambdaWrapper<Shop> wrapper = new MPJLambdaWrapper<>();
        wrapper.eq(Shop::getId, id)
                .leftJoin(User.class ,User::getId, Shop::getUserId)
                .selectAll(Shop.class)
                .select(User::getUsername);

        return shopMapper.selectJoinOne(ShopDTO.class, wrapper);
    }

    @Transactional
    @Override
    public Long addShop(Shop shop) {
        int insert = shopMapper.insert(shop);
        if(insert == 0) throw new GlobalException("添加失败");
        return shop.getId();
    }

    @Transactional
    @Override
    public void updateShop(Shop shop) {
        int update = shopMapper.updateById(shop);
        if(update == 0) throw new GlobalException("更新失败");
    }

    @Transactional
    @Override
    public void deleteShop(Long id) {
        int delete = shopMapper.update(new LambdaUpdateWrapper<Shop>()
                .eq(Shop::getId, id)
                .set(Shop::getStatus, ShopStatus.DELETED));
        if(delete == 0) throw new GlobalException("删除失败");
    }

    @Override
    public List<ShopVO> getShops(List<Long> ids) {
        MPJLambdaWrapper<Shop> wrapper = new MPJLambdaWrapper<>();
        wrapper.in(Shop::getId, ids)
                .leftJoin(Goods.class, Goods::getShopId, Shop::getId)
                .selectCollection(Goods.class, ShopVO::getGoodsList, map -> map
                        .id(Goods::getId)
                        .result(Goods::getTitle)
                        .result(Goods::getPictures)
                        .result(Goods::getPrice));
        return shopMapper.selectJoinList(ShopVO.class, wrapper);
    }
}
